import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';

import {RouterService} from '@kylin/router';
import {HttpService} from '@kylin/http';
import {CustomValidators} from '@kylin/validators';
import {NzMessageService} from 'ng-zorro-antd';


@Component({
    templateUrl: './register.component.html',
    styleUrls: ['./register.component.less']
})
export class RegisterComponent implements OnInit {

    validateForm: FormGroup;
    loading = false;
    state = true;

    constructor(
        private routerService: RouterService,
        private fb: FormBuilder,
        private http: HttpService,
        private nzMessageService: NzMessageService
    ) {
    }

    ngOnInit(): void {
        this.validateForm = this.fb.group({
            username: [null, [Validators.required]],
            password: [null, [Validators.required]],
            rePassword: [null, [Validators.required, this.confirmationValidator]],
            email: [null, [Validators.required, Validators.email]],
        });
    }

    submitForm(): void {
        if (!this.validateForm.valid) {
            return;
        }
        this.loading = true;
        this.http.post('/add/user', this.validateForm.value)
            .then(res => {
                if (res.status === 200) {
                    this.nzMessageService.success('注册成功!');
                    setTimeout(() => {
                        this.routerService.navigate('/login');
                    }, 1500)
                } else {
                    this.nzMessageService.error(res.message);
                }

            })
            .catch(err => {
                this.nzMessageService.error(err['error']['message'] || '注册失败');
            })
    }

    updateConfirmValidator(): void {
        /** wait for refresh value */
        Promise.resolve().then(() => this.validateForm.controls.rePassword.updateValueAndValidity());
    }

    confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
        if (!control.value) {
            return {required: true};
        } else if (control.value !== this.validateForm.controls.password.value) {
            return {confirm: true, error: true};
        }
        return {};
    };

    getCaptcha(e: MouseEvent): void {
        e.preventDefault();
    }
}
